package booyah.web;

import booyah.application.User;
import booyah.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/login")
public class LoginController {

    private UserService userService;

    @Autowired
    public void setPersonService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(method = RequestMethod.GET)                          
    public String login(Model model) {
        model.addAttribute("loginPerson", new User());
        return "login";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String login(@ModelAttribute("loginPerson") User person, Model model, HttpSession session) {

        if (StringUtils.isBlank(person.getEmail())) {
            return "login";
        }

        person = userService.authenticate(person.getEmail(), person.getPassword());

        if (person != null) {
            session.setAttribute("person", person);
            // Set the user
            return "redirect:/controller/home";
        }

        // Set the error
        model.addAttribute("error", "Login Failed");

        return "login";
    }
}
